package com.spark.lola.controller.sup;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spark.lola.constant.SupOrderAction;
import com.spark.lola.entity.pur.OrderInfo;
import com.spark.lola.entity.pur.OrderLocation;
import com.spark.lola.logistics.mapper.LocationInfoMapper;
import com.spark.lola.mapper.pur.OrderInfoMapper;
import com.spark.lola.service.pur.IOrderInfoService;
import com.spark.lola.statistics.entity.StatisticsDestination;
import com.spark.lola.support.ai.service.LicensePlateService;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.core.entity.KafkaMessage;
import com.spark.lola.support.core.param.ExcelParams;
import com.spark.lola.support.mvc.service.ExcelServiceImpl;
import com.spark.lola.support.mybatis.common.QueryCondition;
import com.spark.lola.support.mybatis.controller.BaseController;
import com.spark.lola.support.mybatis.entity.PageParam;
import com.spark.lola.support.mybatis.entity.QueryParam;
import com.spark.lola.support.wms.cache.CollectionCache;
import com.spark.lola.support.wms.configuration.WmsProperties;
import com.spark.lola.support.wms.constant.KafkaTopic;
import com.spark.lola.support.wms.constant.StatisticsGroupType;
import com.spark.lola.support.wms.request.OrderActionRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dengyejun
 * @since 2020-04-24
 */
@RestController
@RequestMapping("/api/pur/analyze")
public class AnalyzeController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(AnalyzeController.class);
    @Autowired
    private OrderInfoMapper currentMapper;
    @Autowired
    private ExcelServiceImpl excelService;
    @Autowired
    private WmsProperties wmsProperties;

    @Autowired
    private LocationInfoMapper locationInfoMapper;

    @RequiresPermissions(value = "m5270")
    @RequestMapping(value = "/findBy", consumes = "application/json")
    public ResponseBean findBy(@RequestBody QueryParam<OrderInfo> queryBean,
                               @SessionAttribute ShiroUser shiroUser) {
        // 是否业务员
        if (wmsProperties.getPurchase().getDutyId().get(1).equals(shiroUser.getDutyId())) {
            bindSelfQuery(queryBean, "o.salesmanId", shiroUser);
        }
        // 是否接货员
        if (wmsProperties.getPurchase().getDutyId().get(2).equals(shiroUser.getDutyId())) {
            bindSelfQuery(queryBean, "o.consigneeId", shiroUser);
        }
        // 当前管理员是否 出纳岗位
        if (wmsProperties.getPurchase().getDutyId().get(4).equals(shiroUser.getDutyId())) {
            bindSelfQuery(queryBean, "o.cashierId", shiroUser);
        }
        // 当前管理员是否 业务主管岗位
        if (wmsProperties.getPurchase().getDutyId().get(0).equals(shiroUser.getDutyId())) {
            List<Long> loactionIds = locationInfoMapper.getIdsByLeaderId(shiroUser.getId());
            if (loactionIds.size() == 0) {
                // 强制过滤
                loactionIds.add(0L);
            }
            String ids = StringUtils.join(loactionIds.toArray(), ",");
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setKey("o.destinationId");
            queryCondition.setOper("in");
            queryCondition.setValue(ids);
            queryBean.getQueryList().add(queryCondition);
        }

        PageParam<OrderInfo> pageParam = queryBean.toPageParam();
        IPage<OrderInfo> page = currentMapper.page(pageParam.getPage(), pageParam.getEntityWrapper());
        page.getRecords().forEach(o -> {
            if (CollectionCache.employees.containsKey(o.getSalesmanId())) {
                o.setSalesman(CollectionCache.employees.get(o.getSalesmanId()));
            }
            o.setProductNames(dealNames(o.getProductNames()));
        });
        return ResponseBean.success(page);
    }

    @RequiresPermissions(value = "m5271")
    @RequestMapping(value = "/excel-out", consumes = "application/json")
    public ResponseBean excelDayOut(@RequestBody ExcelParams<OrderInfo, QueryParam<OrderInfo>> excelParams, @SessionAttribute ShiroUser shiroUser) {
        logger.info("===管理员【{}】申请采购分析报表Excel===START===", shiroUser.getLoginNo());
        // 组装&调整查询条件
        PageParam<OrderInfo> pageParam = super.bindExcel(excelParams, null);
        IPage<OrderInfo> page = currentMapper.page(pageParam.getPage(), pageParam.getEntityWrapper());
        page.getRecords().forEach(o -> {
            if (CollectionCache.employees.containsKey(o.getSalesmanId())) {
                o.setSalesman(CollectionCache.employees.get(o.getSalesmanId()));
            }
            o.setProductNames(dealNames(o.getProductNames()));
        });
        logger.info("===数据量【{}】待生成", page.getTotal());
        ResponseBean responseBean = excelService.create(excelParams.getFileds(), page.getRecords(), OrderInfo.class);
        logger.info("===管理员【{}】申请采购分析报表Excel===END===", shiroUser.getLoginNo());
        return responseBean;
    }

    private String dealNames(String productNames){
        String[] products = productNames.split("\\|");
        String names ="";
        for(String prodcut : products){
            if(StringUtils.isEmpty(names)){
                names = prodcut.split(",")[0];
            }else {
                names += "," + prodcut.split(",")[0];
            }
        }
        return names;
    }
}
